# 第一题、练习作用域之间的转换
a = 1
# 局部变量转化为全局变量
def foo():
    global a    #定以在函数外的变量就是全局变量, 如果在函数体定义那就时局部变量.
    a = 2
    print(a)

foo()

# 局部变量转化为自由变量
def make_foo():
    a = 0
    b = 0
    def foo(value):
        nonlocal a, b
        a += value
        b += 1
        return a / b

    return foo


my_avg=make_foo()
print(my_avg(1))
print(my_avg(2))

#第二题、默写一个装饰器, 用来输出函数的执行时间.
import time
def foo(a, b):
    count = 1
    while True:
        if count >= a ** b:
            break
        count += 1

def clock_it(func, a, b):
    start_time = time.time()
    result = func(a, b)
    end_time = time.time()
    print(f"{func.__name__} execute time:{format(end_time - start_time, '.2f')} s")
    return result
result = clock_it(foo, 10, 7)
print(result)

#第三题、使用装饰器来为斐波那契函数添加缓存
a = {}
def cache_deco(func):
    global a
    def wrap(n):
        if n not in a:
            a[n] = func(n)
        return a[n]
    return wrap

@cache_deco
def fibo(n):
    if n <= 1:
        return n
    else:
        return fibo(n - 1) + fibo(n - 2)

for i in range(0, 10):
    print(fibo(i), end=', ')
print("\n")
print(a)
